# Copyright (c) 2011 anatanokeitai.com(sakurai_youhei)
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# 
# The Software shall be used for Younger than you, not Older.
# 




import sys
import urllib2

import pysugarsync
import pysugarsync.auth
from pysugarsync.exception import PySugarSyncError

request_class={
  "GET":type('classobj',(urllib2.Request,object),{"get_method":lambda self:"GET"}),
  "PUT":type('classobj',(urllib2.Request,object),{"get_method":lambda self:"PUT"}),
  "POST":type('classobj',(urllib2.Request,object),{"get_method":lambda self:"POST"}),
  "DELETE":type('classobj',(urllib2.Request,object),{"get_method":lambda self:"DELETE"})
}

class Connection(object):
  def __init__(self):
    self.token=None

  def do_get(self,url,headers):
    return self._do_request("GET",url,None,headers)

  def do_delete(self,url,headers):
    return self._do_request("DELETE",url,None,headers)

  def do_post(self,url,body,headers):
    return self._do_request("POST",url,body,headers)

  def do_put(self,url,body,headers):
    return self._do_request("PUT",url,body,headers)

  def _do_request(self,method,url,body,headers):
    """
    return response object of urllib2.open()
    """
    if not (method=="GET" or method=="POST" or method=="PUT" or method=="DELETE"):
      raise PySugarSyncError("unsupported method %s"%method)

    if not pysugarsync.auth.is_valid_token(self.token,method,url):
      raise PySugarSyncError("token is invalid %s"%self.token)

    if self.token:
      hs={"Authorization":self.token}
    else:
      hs={}
    if headers:
      hs.update(headers)
    
    req = request_class[method](url,body,hs)

    if pysugarsync.debug_level:
      sys.stderr.write(method)
      #sys.stderr.write(str(req.headers))

    try:
      resp = urllib2.urlopen(req)
    except urllib2.HTTPError, e:
      resp = e

    if resp.code/100  != 200/100:
      sys.stderr.write(str(resp.headers.headers))
      sys.stderr.write(resp.read())
      raise PySugarSyncError("response code is %d"%resp.code)

    if pysugarsync.debug_level:
      sys.stderr.write("->")

    return resp


